<template>
  <view class="treeselectcontent">
    <!-- <view class="openbtn" @click="showTree">
      {{ activeitem.name || "请选择" }}
    </view> -->
    <u-form-item
      :label="item.label"
      borderBottom
      ref="item1"
      :prop="item.value"
      :required="item.required"
    >
      <view
        @click="!disabled && showTree()"
        style="flex: 1; padding: 0"
        ref="formitem"
      >
        {{ activeitem.name || "请选择" }}
      </view>
    </u-form-item>
    <tki-tree
      ref="tkitree"
      :activeid="activeitem.id"
      :range="list"
      :selectParent="false"
      rangeKey="name"
      @confirm="treeConfirm"
      @cancel="treeCancel"
    ></tki-tree>
  </view>
</template>

<script>
import tkiTree from "@/components/tki-tree/tki-tree.vue";
// import { getClassBindingFormsByBindingId } from "@/api/release";
// import { listDept } from "@/api/system/dept";
export default {
  mixins: [uni.$u.mpMixin, uni.$u.mixin],
  components: {
    tkiTree,
  },
  props: {
    item: {
      typeof: Object,
      default: () => {
        return {};
      },
    },
    data: {
      typeof: Object,
      default: () => {
        return {};
      },
    },
    value: {
      typeof: [String, Number, Boolean, Array, Object],
      default: () => {
        return "";
      },
    },
  },
  data() {
    return {
      list: [],
      listDeptdata: [],
    };
  },
  computed: {
    disabled() {
      this.getParentData("u-form")
      return this.parent.disabled;
    },
    activeitem() {
      let r = this.item.list.find((e) => {
        return e.id == this.data[this.item.value];
      });
      return r ? r : {};
    },
   
  },
  watch: {
    item: {
      handler(newValue, oldValue) {
        if (newValue.list) {
          this.list = this.handleTree(this.item.list, "id", "parentId");
          // this.listDeptdata = newValue.list;
        }
        console.log(this.list,"123");
      },
      deep: true,
      immediate: true,
    },
  },
  mounted() {
    // this.init();
  },
  methods: {
    handleTree(data = [], id, parentId, children, rootId) {
      id = id || "id";
      parentId = parentId || "parentId";
      children = children || "children";

      rootId = 0;
      //对源数据深度克隆
      const cloneData = JSON.parse(JSON.stringify(data));
      //循环所有项
      const treeData = cloneData.filter((father) => {
        let branchArr = cloneData.filter((child) => {
          //返回每一项的子级数组
          return father[id] === child[parentId];
        });
        branchArr.length > 0 ? (father.children = branchArr) : "";
        //返回第一层
        return father[parentId] === rootId;
      });
      return treeData !== "" ? treeData : data;
    },
    getAncestorIds(treeData, targetId) {
      const nodeMap = {};

      // 遍历整个树结构，将每个节点存入nodeMap
      function traverse(nodes) {
        if (!nodes || !Array.isArray(nodes)) return;
        for (const node of nodes) {
          nodeMap[node.id] = node;
          traverse(node.children);
        }
      }

      traverse(treeData); // 初始化nodeMap

      const targetNode = nodeMap[targetId];
      if (!targetNode) return []; // 如果未找到目标节点，返回空数组

      const ancestors = [targetId];
      let currentNode = targetNode;

      // 循环查找父节点直到根节点（parentId为0）
      while (currentNode.parentId !== 0) {
        const parentId = currentNode.parentId;
        const parent = nodeMap[parentId];
        if (parent) {
          ancestors.push(parent.id);
          currentNode = parent;
        } else {
          break; // 如果父节点不存在，停止查找
        }
      }

      return ancestors.reverse();
    },
    // 确定回调事件
    async treeConfirm(e) {
      console.log(e);
      if (e.length == 1) {
        let list = this.getAncestorIds(this.list, e[0].id);
        console.log(list, "list");
        // this.activeitem = e[0];
        // level1Type
        // this.$emit("input", String(e[0].id));
        this.$emit("change", {
          level1Type: list[0],
          level2Type: list[1],
          level3Type: list[2],
        });
        uni.$u.formValidate(this.$refs.formitem, "blur");
        
        // this.$emit("change", {
        //   formsJsonRule: rule,
        // });
        // console.log(reqData, "reqData");
      }
    },
    // 取消回调事件
    treeCancel(e) {
      console.log(e);
    },
    // 显示树形选择器
    showTree() {
      this.$refs.tkitree._show();
    },
  },
};
</script>
<style lang="scss" scoped>
.treeselectcontent {
  flex: 1;

  .openbtn {
    display: flex;
    // justify-content: center;

    align-items: center;
    // height: 100%;
    border: 1px solid #e5e5e5;
    position: relative;
    height: 72rpx;
    padding: 0 20rpx;
    border-radius: 10rpx;

    .iconclear {
      position: absolute;
      right: 10rpx;
    }
  }
}
</style>
